package com.jasmine.bjstkserver.server.article.log.viewlog;

import cn.hutool.core.util.ArrayUtil;
import com.jasmine.core.util.BeanUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;


/**
 * 异步监听日志事件
 * @author jasmineXz
 */
@Component
public class ViewLogListener {
	private static final Logger log = LoggerFactory.getLogger(ViewLogListener.class);

	private static final String TYPE_CLICK   = "CLICK";
	private static final String TYPE_VIEW    = "VIEW";
	private static final String TYPE_APPLAUD = "APPLAUD";


	@Autowired
	private ArticleViewLogViewHandler articleViewLogViewHandler;

	@Autowired
	private	ArticleViewLogClickHandler articleViewLogClickHandler;

	@Autowired
	private ArticleViewLogApplaudHandler articleViewLogApplaudHandler;

	/**
	 * 记录文章点击日志
	 * @param event 事件
	 */
	@Async
	@EventListener(ArticleViewLogEvent.class)
	public void saveClickLog(ArticleViewLogEvent event) throws Exception {
		if (!ArrayUtil.containsIgnoreCase(event.getTypes(),TYPE_CLICK))
			return;
		articleViewLogClickHandler.execute(beNewLog(event));
	}

	/**
	 * 记录文章阅读日志
	 * @param event 事件
	 */
	@Async
	@EventListener(ArticleViewLogEvent.class)
	public void saveViewLog(ArticleViewLogEvent event) throws Exception {
		if (!ArrayUtil.containsIgnoreCase(event.getTypes(),TYPE_VIEW))
			return;
		articleViewLogViewHandler.execute(beNewLog(event));
	}

	/**
	 * 记录文章点赞日志
	 * @param event 事件
	 */
	@Async
	@EventListener(ArticleViewLogEvent.class)
	public void saveApplaudLog(ArticleViewLogEvent event) throws Exception {
		if (!ArrayUtil.containsIgnoreCase(event.getTypes(),TYPE_APPLAUD))
			return;
		articleViewLogApplaudHandler.execute(beNewLog(event));
	}


	private ViewLogEntity beNewLog (ArticleViewLogEvent event) throws Exception {
		return BeanUtil.copyObject(event.getSource(),ViewLogEntity.class);
	}


    @PostConstruct
    public void init() {
        log.info("[BJSTK] 监听器启动");
    }


}
